package com.building.hcrm.ui;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.base.BaseAsyncTask;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.common.Utils;
import com.building.hcrm.model.PlanDetail;
import com.building.hcrm.model.SysUser;
import com.building.hcrm.ui.customcontrols.ComStaffSelector;
import com.building.hcrm.wcf.TaskServiceProxy;

public class TaskAddActivity extends BaseActivity
{
	private EditText _txtTaskContent;
	private Button _btnSave;
	private Button _btnSaveBack;
	private ComStaffSelector _selector;

	private Button _btnDateFrom;
	private Button _btnDateTo;
	private ImageButton _imgBtnRe;
	private TextView _txtTitle;
	private ImageButton _imgBtnTitleRight;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_add);
		InitTitle();
		_selector = (ComStaffSelector) findViewById(R.id.staff_selector);
		_selector.load(ComStaffSelector.DISPLAY_TYPE_SUB);
		FromToTimer(null, null);
		_txtTaskContent = (EditText) findViewById(R.id.txt_task_content);
		_btnSave = (Button) findViewById(R.id.btn_task_save);
		_btnSave.setOnClickListener(SaveClickListener);
		_btnSaveBack = (Button) findViewById(R.id.btn_task_save_back);
		_btnSaveBack.setOnClickListener(SaveBackClickListener);
	}

	private void InitTitle()
	{
		_imgBtnRe = (ImageButton) findViewById(R.id.imgbtn_home);
		_imgBtnRe.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// TODO 自动生成的方法存根
				finish();
			}
		});
		_txtTitle = (TextView) findViewById(R.id.titlePageName);
		_txtTitle.setText(R.string.task_add_title);
		_imgBtnTitleRight = (ImageButton) findViewById(R.id.imgbtn_save);
		_imgBtnTitleRight.setVisibility(View.INVISIBLE);
	}

	private void FromToTimer(Date dtFrom, Date dtTo)
	{
		try
		{
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdfdate;

			_btnDateFrom = (Button) findViewById(R.id.btn_date_selector_from);
			_btnDateFrom.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateFrom.setText(sdfdate.format(dtFrom == null ? calendar.getTime() : dtFrom));

			_btnDateTo = (Button) findViewById(R.id.btn_date_selector_to);
			_btnDateTo.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateTo.setText(sdfdate.format(dtTo == null ? calendar.getTime() : dtTo));

		}
		catch (Exception e)
		{
			Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
		}
	}

	// 日期选择事件监听：OnClickListener
	private View.OnClickListener DatePickerButtion_Click = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			try
			{
				if (Utils.isFastDoubleClick())
					return;
				final Button button = (Button) v;

				// 日期設定
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int monthOfYear = calendar.get(Calendar.MONTH);
				int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
				if (button.getText().length() > 0)
				{
					year = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[0]);
					monthOfYear = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[1]) - 1;
					dayOfMonth = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[2]);
				}

				// 日付選択ﾀﾞｲｱﾛｸﾞ：OnDateSetListener
				DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
				{
					private int _year, _monthOfYear, _dayOfMonth;

					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
					{
						try
						{
							if (_year != year || _monthOfYear != monthOfYear || _dayOfMonth != dayOfMonth)
							{
								_year = year;
								_monthOfYear = monthOfYear;
								_dayOfMonth = dayOfMonth;
								Calendar calendar = Calendar.getInstance();
								calendar.set(year, monthOfYear, dayOfMonth);
								SimpleDateFormat sdf = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
								Date dtCheck = new Date(sdf.format(calendar.getTime()));
								if (CheckDateValue(button, dtCheck))
								{
									button.setText(sdf.format(calendar.getTime()));
								}
							}
						}
						catch (Exception e)
						{
							Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
						}
					}

				};

				// 日付選択ﾀﾞｲｱﾛｸﾞ作成＆表示
				DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(), dateSetListener, year,
						monthOfYear, dayOfMonth);
				datePickerDialog.show();
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}
	};

	private boolean CheckDateValue(Button button, Date checkDate)
	{
		Date compareDate = null;
		String alarmText = null;

		// 触发控件为起始时间
		if (button.getId() == _btnDateFrom.getId())
		{
			compareDate = new Date(_btnDateTo.getText().toString());
			if (checkDate.after(compareDate))
			{
				alarmText = "起始时间必须小于或等于结束时间";
				Toast.makeText(TaskAddActivity.this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		else if (button.getId() == _btnDateTo.getId())
		{
			compareDate = new Date(_btnDateFrom.getText().toString());
			if (checkDate.before(compareDate))
			{
				alarmText = "结束时间必须大于或等于起始时间";
				Toast.makeText(TaskAddActivity.this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}

		return true;
	}

	private View.OnClickListener SaveClickListener = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			SaveAction(false);
		}
	};

	private void SaveAction(final Boolean bBack)
	{
		PlanDetail saveModel = new PlanDetail();
		saveModel.UserNumDo = _selector.getCurrentStaff().getUserNum();
		saveModel.UserNumSet = User.getInstance(TaskAddActivity.this).getUserNum();
		saveModel.PlanContent = _txtTaskContent.getText().toString();
		saveModel.PlanStartTime = ComFunc.GetDateByString(_btnDateFrom.getText().toString(), ComConst.DATE_FORMAT);
		saveModel.PlanEndTime = ComFunc.GetDateByString(_btnDateTo.getText().toString(), ComConst.DATE_FORMAT);

		new BaseAsyncTask<PlanDetail, String, Boolean>(TaskAddActivity.this, "提交...")
		{
			@Override
			protected void onPreExecute()
			{
				super.onPreExecute();
			}

			@Override
			protected Boolean doInBackground(PlanDetail... params)
			{
				Boolean re = false;
				if (null != params && params.length > 0)
				{
					try
					{
						re = TaskServiceProxy.getInstance(TaskAddActivity.this).TaskCreate(params[0]);
					}
					catch (Exception e)
					{
						Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
					}
				}
				return re;
			}

			@Override
			protected void onPostExecute(Boolean result)
			{
				super.onPostExecute(result);
				if (result)
				{
					Toast.makeText(TaskAddActivity.this, "提交成功！", Toast.LENGTH_SHORT).show();
					if (bBack)
					{
						finish();
					}
				}
				else
				{
					Toast.makeText(TaskAddActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
				}
			}
		}.execute(saveModel);
	}

	private View.OnClickListener SaveBackClickListener = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			SaveAction(true);
		}
	};
}
